package gameobjects
{
	import assets.Globals;
	import assets.Images;
	
	import com.greensock.TweenMax;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.sensors.Accelerometer;
	import flash.utils.Timer;

	public class Tower extends GameObject
	{
		protected var mySprite:Sprite = new Sprite();
		
		protected var attackRate:Number;
		protected var shootTimer:Timer;
		protected var Active:Boolean = false;
		protected var bar:Bar;
		
		protected var shadow:Sprite = new Sprite();
		
		private const alphaWhenNotActive:Number = 0.72;		
		
		public function Tower(attackRate:Number)
		{
			super(100);
			this.attackRate = attackRate;
			shootTimer = new Timer(1000/attackRate);
			this.bar = new Bar(this,0,0);
			
			alpha = alphaWhenNotActive;
			
			cs.x = 32;
			cs.y = 32;
			cs.graphics.beginFill(0xFF0000);
			cs.graphics.drawCircle(0, 0, 20);
			cs.graphics.endFill();
			cs.alpha = 0;
			
			// shadow
			addChild(Globals.shadow());
			
			//
			addChild(cs);
			addChild(mySprite);
		}
		
		public function pause():void
		{
			shootTimer.stop();
		}
		
		public function resume():void
		{
			shootTimer.start();
		}
		
		override public function destroy():void
		{
			Globals.towers.splice(Globals.towers.indexOf(this), 1);
			Globals.towersMap.removeTower(fieldX, fieldY);
			
			var destructionTimer:Timer = new Timer(4000, 1);
			destructionTimer.addEventListener("timer", destruction);
			destructionTimer.start();
			
			if (bar.parent == this) removeChild(bar);
			
			shootTimer.stop();
			shootTimer.removeEventListener("timer", timerHandler);
		}
		
		private function destruction(event:TimerEvent):void
		{
			TweenMax.to(this, 1, { alpha:0, y: this.y-40, onComplete:finalDestruction });
			TweenMax.to(shadow, 1, { alpha:0, y: shadow.y+40 });
		}
		
		private function finalDestruction():void
		{
			super.destroy();
		}
		
		public function Activate():void
		{
			shootTimer.start();
			shootTimer.addEventListener("timer", timerHandler);
			Active = true;
			alpha = 1;
		}
		
		protected function timerHandler(event:TimerEvent):void
		{
		}
		
		public function Deactivate():void
		{
			Active = false;
			shootTimer.stop();
			alpha = alphaWhenNotActive;
		}
		
		public function isActive():Boolean
		{
			return Active;
		}
		
		public function hide():void
		{
			alpha = 0;
		}
		public function show():void
		{
			if (Active)
				alpha = 1;
			else
				alpha = alphaWhenNotActive;
		}
		override public function decreaseHealth(by:Number):Boolean
		{
			var result:Boolean = super.decreaseHealth(by);
			bar.update();
			return result;
		}
		
		public function getBar():Bar
		{
			return bar;
		}
	}
}